//
//  ShopListViewContrller.m
//  uneed
//
//  Created by apple on 4/11/12.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "ShopListViewContrller.h"
#import "JSONKit.h"
#import "MapViewCtrl.h"
#import "ReviewListViewCtrl.h"
#import "ShopInfoViewCtrl.h"
#import <SDWebImage/UIImageView+WebCache.h>

@implementation ShopListViewContrller


@synthesize shopName,shopSubName,shopImage,distance;
@synthesize shoplists,shopClasses;
@synthesize tvCell,useDarkBackground;
@synthesize api2gets;
@synthesize loadFooterView = _loadFooterView;

#define DARK_BACKGROUND  [UIColor colorWithRed:151.0/255.0 green:152.0/255.0 blue:155.0/255.0 alpha:1.0]
#define LIGHT_BACKGROUND [UIColor colorWithRed:172.0/255.0 green:173.0/255.0 blue:175.0/255.0 alpha:1.0]

#define kCustomRowHeight    60.0
#define kCustomRowCount     1

- (void)dealloc
{
    
    _refreshHeaderView = nil;
    _loadFooterView =nil;
	[api2gets release];
	api2gets = nil;
    [tvCell release];
	[shopClasses release];
	[shoplists release];
	shoplists = nil;
	
	[distance release];
	[shopImage release];
	[shopSubName release];
	[shopName release];
	
    [super dealloc];
}

/*
- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if (self = [super initWithStyle:style]) {
    }
    return self;
}
*/

- (void)toShopAdd {
	if ([[NSUserDefaults standardUserDefaults] boolForKey:@"is_login"]) {
	ShopAddViewCtrl *shopAddViewCtrl = [[ShopAddViewCtrl alloc]init];
	shopAddViewCtrl.title = @"添加商家";
	[self.navigationController pushViewController:shopAddViewCtrl animated:YES];
	[shopAddViewCtrl release];
	}
	act_no = 0;
}

- (void)actShopAdd {
	//	RootGroupView *rootGroupView = [[RootGroupView alloc] initWithStyle:UITableViewStylePlain];
//	RootGroupView *rootGroupView = [[RootGroupView alloc] initWithStyle:[appDelegate getTableViewStyle]];

	if (act_no>0) return;
	act_no = act_shopadd;
	NSUserDefaults *_userdef = [NSUserDefaults standardUserDefaults];
	if ([_userdef boolForKey:@"is_login"] == NO) {
		LoginViewController *loginViewCtrl = [[LoginViewController alloc]init];
//		[self.navigationController pushViewController:loginViewCtrl animated:YES];
		[self presentModalViewController:loginViewCtrl animated:YES];
		[loginViewCtrl release];
		return;		
	} else {
		[self toShopAdd];
	}
}

//- (void)showHUD {
//	api_count++;
//	if (HUD==nil) {
//		UIActivityIndicatorView *_aiv = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
//		
//		HUD = [[UIAlertView alloc]initWithTitle:@"正在加载中" 
//										message:@"" 
//									   delegate:nil 
//							  cancelButtonTitle:@"取消"
//							  otherButtonTitles:nil];
//		_aiv.frame = CGRectMake(0, 0, 50, 50);
//		[HUD addSubview:_aiv];
//	}
//	[HUD show];
//	
//}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    if (_refreshHeaderView == nil) {
		
		EGORefreshTableHeaderView *view = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - self.tableView.bounds.size.height, self.view.frame.size.width, self.tableView.bounds.size.height)];
		view.delegate = self;
		[self.tableView addSubview:view];
		_refreshHeaderView = view;
		[view release];
		
	}
	
	//  update the last update date
	[_refreshHeaderView refreshLastUpdatedDate];

    if (_loadFooterView == nil) {
		
		LoadingMoreFooterView *foot_view = [[LoadingMoreFooterView alloc] initWithFrame:CGRectMake(0,0, self.view.frame.size.width, 44.0f)];
//		foot_view.delegate = self;
        self.loadFooterView = foot_view;
		[foot_view release];
        
//		[self.view addSubview:self.loadFooterView];
		self.tableView.tableFooterView = self.loadFooterView;
	}

    
    
    
    
	act_no = 0;
	api_count = 0;
	self.navigationItem.title = @"附近商家";

//	UIBarButtonItem *btnShopAdd = [[UIBarButtonItem alloc] 
//									   initWithBarButtonSystemItem:UIBarButtonSystemItemReply target:self action:@selector(loadMusicAction)];
//	self.navigationItem.rightBarButtonItem = btnShopAdd;
//	[btnShopAdd release];
	
    UIBarButtonItem *addButton = [[[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"添加商家", @"")
																   style:UIBarButtonItemStyleBordered
																  target:self
																  action:@selector(actShopAdd)] autorelease];
	self.navigationItem.rightBarButtonItem = addButton;
	
	self.shopClasses = [[NSMutableDictionary alloc]init];
    self.tableView.rowHeight = kCustomRowHeight;

	if (shoplists==NULL) shoplists = [[NSMutableArray alloc]init];

	[self reloadTableViewDataSource];


}

#pragma mark -
#pragma mark Data Source Loading / Reloading Methods

- (void)reloadTableViewDataSource{
	
    if (_reloading || page_isend) return;
	//  should be calling your tableviews data source model to reload
	//  put here just for demo
//	_reloading = YES;
	//如果网络存在则加载数据
//	if ([CheckNetwork isExistenceNetwork]) {
//		data = [[MyDataSource fetchLibraryInformation] retain];
//	}
    
    
    if (!_loadingmore) {
        currentPage = 1;
//        [shoplists removeAllObjects];
        page_isend = FALSE;
    }
    
	_reloading = YES;

    
    howcanApi2Get *_shoplist_api = [api2gets objectForKey:API_GetShopLists];
    if (_shoplist_api==nil) {
        _shoplist_api = [[howcanApi2Get alloc]init];
        [api2gets setObject:_shoplist_api forKey:API_GetShopLists];
    }
    //        [_shoplist_api cancelApi];
    self.title = [NSString stringWithFormat:@"%.2f-%.2f", loc_lat,loc_lng];
    [_shoplist_api getShopListsWithLat:loc_lat*1000000 withLng:loc_lng*1000000 withPage:currentPage withDelegate:self withIndex:API_GetShopLists];
    
//    [_shoplist_api release];
    
//    if(_loadingmore)
//    {
//        _loadingmore = NO;
//        self.loadFooterView.showActivityIndicator = NO;
//    }
    
//    [self.tableView reloadData];
    
//    [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:3.0];

	
	
}


- (void)doneLoadingTableViewData{
	
	//  model should call this when its done loading
	_reloading = NO;
    _loadingmore = NO;
	[_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.tableView];
    self.loadFooterView.showActivityIndicator = NO;
    
    if (page_isend) {
        self.tableView.tableFooterView = nil;
    } else {
        self.tableView.tableFooterView = self.loadFooterView;
    }
    
    [self.tableView reloadData];
 
    
//    self.tableView.contentSize = CGSizeMake(self.view.frame.size.width, self.tableView.contentSize.height + 44.0f);

//    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 44, 0);
//    _loadFooterView.frame = CGRectMake(0,self.tableView.contentSize.height, self.view.frame.size.width, 44.0f);
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{	

	[_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView*)scrollView
{

}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	
   
	[_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];

	
    
    if (!decelerate)
	{
//        [self loadImagesForOnscreenRows];
    }

}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    float bottomEdge = scrollView.contentOffset.y + scrollView.frame.size.height;
    
    if (bottomEdge >= scrollView.contentSize.height ) 
    {
        if (_loadingmore || page_isend) return;
        
        NSLog(@"load more");
        _loadingmore = YES;
        self.loadFooterView.showActivityIndicator = YES;
        
        currentPage ++;
        [self performSelector:@selector(reloadTableViewDataSource) withObject:self afterDelay:1.0f]; //make a delay to show loading process for a while
    }
}


#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
	if (_loadingmore) return;
	_loadingmore = NO;
    page_isend = NO;
    [self reloadTableViewDataSource];
	
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
	
	return _reloading; // should return if data source model is reloading
	
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
	
	return [NSDate date]; // should return date data source was last changed
	
}




- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}




- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
	if (act_no>0) {
		if (act_no==act_shopadd) {
			[self toShopAdd];
		}
	}
}


/*
- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
//	NSArray *allDownloads = [self.imageDownloadsInProgress allValues];
//    [allDownloads makeObjectsPerformSelector:@selector(cancelDownload)];

}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
    _refreshHeaderView=nil;
}


#pragma mark Table view methods


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	
	int count = [shoplists count];
	
	// ff there's no data yet, return enough rows to fill the screen
    if (count == 0)
	{
        return kCustomRowCount;
    }
    return count;
	
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    static NSString *CellIdentifier = @"ShopCellViewCtrl";
	
	static NSString *PlaceholderCellIdentifier = @"PlaceholderCell";

	int nodeCount = [shoplists count];
	
	if (nodeCount == 0)
	{
		UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:PlaceholderCellIdentifier];
        if (cell == nil)
		{
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
										   reuseIdentifier:PlaceholderCellIdentifier] autorelease];   
            cell.detailTextLabel.textAlignment = UITextAlignmentCenter;
			cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
		if (indexPath.row == 0)
		cell.detailTextLabel.text = @"数据加载中...";
		
		return cell;
    }
	
//	if (indexPath.row >= [shoplists count] -1) {
//		if (!page_isend && !is_loaddate) {
//			currentPage ++;
//			is_loaddate = TRUE;
//			
//			howcanApi2Get *_shoplist_api = [api2gets objectForKey:@"shoplists"];
//			if (_shoplist_api==nil) {
//				_shoplist_api = [[howcanApi2Get alloc]init];
//			}
//			
//			[self showHUD];
//
//			[_shoplist_api getShopListsWithLat:loc_lat*1000000 withLng:loc_lng*1000000 withPage:currentPage withDelegate:self withIndex:0];
//		}
//	}
	
	
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {       
//        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
//        [[NSBundle mainBundle] load
//        [[UINib nibWithNibName:@"ShopCellViewCtrl" bundle:nil]instantiateWithOwner:self options:nil];
		NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ShopCellViewCtrl" owner:self options:nil];
		if ([nib count]>0)
			cell = self.tvCell;
//		self.tmpCell = nil;
        
        
    }
    
	Shop *ashop = [shopClasses objectForKey:indexPath];
	if (ashop==NULL) {    
		NSDictionary *ashopdic = [shoplists objectAtIndex:[indexPath row]];
		Shop *_ashop = [[Shop alloc]init];
		_ashop.sid = [[ashopdic objectForKey:@"sid"]intValue] ;
		_ashop.name = [ashopdic objectForKey:@"name"];
		_ashop.subname = [ashopdic objectForKey:@"subname"];
		_ashop.thumb = [ashopdic objectForKey:@"thumb"];
		_ashop.distance = [ashopdic objectForKey:@"distance"];
		_ashop.description = [ashopdic objectForKey:@"description"];
		_ashop.categoryname = [ashopdic objectForKey:@"categoryname"];
		_ashop.map_lat = [[ashopdic objectForKey:@"map_lat"] floatValue];
		_ashop.map_lng = [[ashopdic objectForKey:@"map_lng"] floatValue];
		[shopClasses setObject:_ashop forKey:indexPath];
		[_ashop release];
        ashop = [shopClasses objectForKey:indexPath];

	}
    [shopName setText:ashop.name];
    [shopName sizeToFit];
    if (![ashop.subname isEqual:@""]) {
        [shopSubName setText:[NSString stringWithFormat:@"(%@)",ashop.subname]];
        [shopSubName sizeToFit];
        shopSubName.frame = CGRectMake(shopName.frame.origin.x + shopName.frame.size.width+5,shopSubName.frame.origin.y,shopSubName.frame.size.width,shopSubName.frame.size.height);
        
    } else {
        [shopSubName setText:@""];
    }//    cell.shopName.frame.origin.x + cell.shopName.frame.size.width;
	float i_distance = [ashop.distance floatValue];
	if (i_distance>=100000) {
		[distance setText:[NSString stringWithFormat:@"%.0f公里",i_distance/1000]];
	} else if (i_distance>=10000) {
			[distance setText:[NSString stringWithFormat:@"%.1f公里",i_distance/1000]];
	} else if (i_distance>=1000) {
			[distance setText:[NSString stringWithFormat:@"%.2f公里",i_distance/1000]];
	} else {
			[distance setText:[NSString stringWithFormat:@"%.0f米",i_distance]];
	} 
//	[distance setText:[NSString stringWithFormat:@"%@",ashop.distance]];
//	[distance sizeToFit];
    // Set up the cell...
    
    
    NSString *imgUrl = ashop.thumb;
    if (![imgUrl isEqual:@""]) {
        imgUrl = [NSString stringWithFormat:@"%@%@",M_ROOT,imgUrl];
    }	
    
//	if (ashop.shopimg==NULL)
//	{
//		if (self.tableView.dragging == NO && self.tableView.decelerating == NO)
//		{
//			NSString *imgUrl = ashop.thumb;
//			if (![imgUrl isEqual:@""]) {
//				imgUrl = [NSString stringWithFormat:@"%@%@",M_ROOT,imgUrl];
//			[self startImageDownload:imgUrl forIndexPath:indexPath];
//			}
//		}
//		// if a download is deferred or in progress, return a placeholder image
//		[shopImage setImage:[UIImage imageNamed:@"Placeholder_loading.png"]];                
//	}
//	else
//	{
//		[shopImage setImage:ashop.shopimg]; 
//
////		cell.imageView.image = appRecord.appIcon;
//	}
//    [shopImage setImageWithURL:[NSURL URLWithString:imgUrl] placeholderImage:[UIImage imageNamed:@"placeholder_loading"]];
    UIImageView *tmpimg = [[UIImageView alloc]initWithFrame:shopImage.frame];
    [tmpimg setImageWithURL:[NSURL URLWithString:imgUrl] placeholderImage:[UIImage imageNamed:@"placeholder_loading"]];
    
     int kAppIconWidth = shopImage.frame.size.width;
    if (tmpimg.image.size.width>80) {
     CGSize itemSize = CGSizeMake(kAppIconWidth, tmpimg.image.size.height*kAppIconWidth/tmpimg.image.size.width);
     UIGraphicsBeginImageContext(itemSize);
     CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
     [tmpimg.image drawInRect:imageRect];
     shopImage.image = UIGraphicsGetImageFromCurrentImageContext();
     UIGraphicsEndImageContext();
    } else {
        shopImage.image = tmpimg.image;
    }
    [tmpimg release];
                                      
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
	// [self.navigationController pushViewController:anotherViewController];
	// [anotherViewController release];
	
	Shop *_ashop = [shopClasses objectForKey:indexPath];
	if (_ashop!=NULL) {
		ShopInfoViewCtrl *_viewCtrl = [[ShopInfoViewCtrl alloc]init];
		_viewCtrl.title = [NSString stringWithFormat:@"%@",[_ashop name]];
		if ([[_ashop subname] length]>0) {
			_viewCtrl.title = [_viewCtrl.title stringByAppendingFormat:@"(%@)",[_ashop subname]];	
		}
		_viewCtrl.shopid = [_ashop sid];
		
		[self.navigationController pushViewController:_viewCtrl animated:YES];
		[_viewCtrl release];

//		ReviewListViewCtrl *_viewCtrl = [[ReviewListViewCtrl alloc]init];
//		[self.navigationController pushViewController:_viewCtrl animated:YES];
//		[_viewCtrl release];
	
	}	
	
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
//    cell.backgroundColor = ((ShopCellViewCtrl *)cell).useDarkBackground ? DARK_BACKGROUND : LIGHT_BACKGROUND;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

//	UITableViewCell *cell=[self tableView: tableView cellForRowAtIndexPath: indexPath];
//
//    CGFloat height=cell.frame.size.height; 
//
//	NSLog(@"cell height is %.f at %d", height, [indexPath row]);
//	return height;
	return 73;    
}


-(void)  errorCallback:(NSArray*) error {
    
}

/*数据下载完毕 */
-(void)  completedCallback:(NSArray *) data {
    _reloading = false;
	if ([data count]<2) return;
    [api2gets removeObjectForKey:[data objectAtIndex:0]];
    
	NSString *_data = [NSString stringWithFormat:@"%@",[data objectAtIndex:1]];

    NSMutableDictionary *jsondic = [_data objectFromJSONString];
	NSNumber *errCode = [jsondic objectForKey:@"errCode"];
	if ([errCode intValue]==0) {
//		NSLog([NSString stringWithFormat:@"%i",[[jsondic objectForKey:@"errMessage"] count]]);
		if ([[jsondic objectForKey:@"errMessage"] count]<20) page_isend = TRUE;
        if (!_loadingmore) {
            [shoplists removeAllObjects];
            [shopClasses removeAllObjects];
        }
		[shoplists addObjectsFromArray:[jsondic objectForKey:@"errMessage"]];
		[self.tableView reloadData];
	}
    
    [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:1.0];
  
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
	[super locationManager:manager didUpdateToLocation:newLocation fromLocation:oldLocation];
	if (fabs([newLocation coordinate].latitude -[oldLocation coordinate].latitude)>0.1 || fabs([newLocation coordinate].longitude - [oldLocation coordinate].longitude)>0.1) {
		_loadingmore = NO;
        page_isend = NO;
        _reloading = NO;
        [self reloadTableViewDataSource];
   
    }

	
}


@end

